package dataImport.action;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import dataImport.action.abstracts.AbstractEntityReader;
import dataImport.action.manager.EntityReaderManager;
import dataImport.exception.MissingAttributeException;
import dataImport.model.Command;
import dataImport.model.CustomAction;
import dataImport.model.Text;
import dataImport.model.abstracts.AbstractEntity;


public class CustomActionReader extends AbstractEntityReader {

	private static final long serialVersionUID = 1212405523847320486L;

	public static final String ENTITY_NAME = "action";

	private static final String ATTRIBUTE_COMMAND_ID = "command";
	
	private static final String ATTRIBUTE_REPLACE = "replace";

	public CustomActionReader(final EntityReaderManager entityReaderManager) {
		super(entityReaderManager);
	}

	@Override
	protected AbstractEntity createEntity(final Element element) {
		final String id = element.getAttribute(ATTRIBUTE_ID);
		final String replace = element.getAttribute(ATTRIBUTE_REPLACE);
		final String commandId = element.getAttribute(ATTRIBUTE_COMMAND_ID);

		this.verifyRestrictions(id, commandId, replace);
		
		final CommandReader commandReader = super.getEntityReaderManager().getCommandReader();
		final Command command = (Command) commandReader.getEntityWithId(commandId);
		
		Text pattern = null;
		if (!replace.isEmpty()) {
			pattern = new Text(command.getPattern(), super.getEntityReaderManager(), replace);
		}
		else {
			pattern = new Text(command.getPattern());
		}

		return new CustomAction(id, pattern);
	}

	@Override
	public void read(final Document document) {
		this.read(CustomActionReader.ENTITY_NAME, document);
	}

	protected final void verifyRestrictions(final String id, final String commandId, final String replace) {
		super.verifyRestrictions(id);

		if (commandId.isEmpty()) {
			throw new MissingAttributeException(ATTRIBUTE_COMMAND_ID);
		}
		
		final CommandReader commandReader = super.getEntityReaderManager().getCommandReader();
		final Command command = (Command) commandReader.getEntityWithId(commandId);
		
		if (Text.hasReplace(command.getPattern()) && replace.isEmpty()) {
			throw new MissingAttributeException(ATTRIBUTE_REPLACE);
		}
	}
}
